package com.example.memorypoint.activity;


import static com.kongzue.dialogx.interfaces.BaseDialog.getContext;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.example.memorypoint.DateBase.DiaryDatabase;
import com.example.memorypoint.R;
import com.example.memorypoint.adapter.FragmentAdapter;
import com.example.memorypoint.entity.Diary;
import com.example.memorypoint.fragment.DiaryFragment;
import com.example.memorypoint.utils.StackPageTransformer;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.makeramen.roundedimageview.RoundedImageView;

import org.checkerframework.framework.qual.DefaultQualifier;
import org.w3c.dom.Text;


import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private final List<DiaryFragment> diaryFragments = new ArrayList<>();
    private List<Diary> diaryList = new ArrayList<>();
    private ViewPager viewPager;
    private FragmentAdapter diaryPagerAdapter;
    private DrawerLayout drawerLayout;
    private static MainActivity instance;
    private DiaryDatabase database;
    NavigationView navigationView;
    Toolbar toolbar;
    private RoundedImageView imageView;
    private TextView tv_name;
    FloatingActionButton addButton;
    FloatingActionButton aiChat;
    ImageButton  selectDateButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById();
        instance = this;
        // 从数据库中搜索diaryList
        database = new DiaryDatabase(getBaseContext());
        initFragmentList();
        initAdapter();
        initMenu();
    }

    private void initFragmentList() {
        diaryList = database.getDairyList();  // 直接获取最新数据
        diaryFragments.clear();  // 避免重复添加
        for (Diary info : diaryList) {
            diaryFragments.add(DiaryFragment.getInstance(info));
        }
        if (diaryPagerAdapter != null) {
            diaryPagerAdapter.notifyDataSetChanged();
        }
    }


    @SuppressLint("ResourceType")
    private void findViewById() {
        aiChat = findViewById(R.id.chat);
        toolbar = findViewById(R.id.toolbar);
        drawerLayout = findViewById(R.id.drawer_layout);
        viewPager = findViewById(R.id.viewPager);
        addButton = findViewById(R.id.add);
        FloatingActionButton stasticsButton = findViewById(R.id.stastics);
        selectDateButton=findViewById(R.id.btn_select_date);
        addButton.setOnClickListener(this);
        stasticsButton.setOnClickListener(this);
        aiChat.setOnClickListener(this);
        selectDateButton.setOnClickListener(this);
    }

    public void initAdapter() {
        //viewpager中显示的是list的倒序
        viewPager.setPageTransformer(true, new StackPageTransformer(viewPager));
        //设置适配器
        diaryPagerAdapter = new FragmentAdapter(getSupportFragmentManager(), diaryFragments);
        viewPager.setAdapter(diaryPagerAdapter);
        //Pager之间的间距
        viewPager.setPageMargin(20);
        //预加载
        viewPager.setOffscreenPageLimit(2);
        //默认第一张图 左右都有图
        viewPager.setCurrentItem(0);
    }

    private String getToday() {
        LocalDate today = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        return today.format(formatter);
    }



    // 添加DiaryFragment并跳转到该Fragment
    private void addDiaryFragment() {
        LocalTime currentTime = LocalTime.now();
        String time = addZero(currentTime.getHour()) + ":" + addZero(currentTime.getMinute()) + ":" + addZero(currentTime.getSecond());

        int id = database.insertDiary(getToday(), time);
        if (id == -1) {
            Toast.makeText(this, "日记创建失败", Toast.LENGTH_SHORT).show();
            return;
        }

        Diary diary = new Diary(getToday(), id, -1, time);

        diaryFragments.add(0, DiaryFragment.getInstance(diary));
        diaryPagerAdapter.notifyDataSetChanged(); // 只刷新Adapter，不重置ViewPager
        viewPager.setCurrentItem(0, true);

        // 跳转到写日记页面
        Intent intent = new Intent(this, WriteActivity.class);
        intent.putExtra(WriteActivity.EXTRA_DIARY_ID, id);
        intent.putExtra(WriteActivity.EXTRA_DIARY_DATE, getToday());
        startActivity(intent);
    }



    private String addZero(int num) {
        if (num <= 9) {
            return "0" + num;
        }
        return String.valueOf(num);
    }

    @Override
    protected void onResume() {
        flushData(imageView, tv_name);
         super.onResume();
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.add) {
            addDiaryFragment();
        } else if (id == R.id.stastics) {
            startActivity(new Intent(this, UserActivity.class));
        } else if (id == R.id.chat) {
            startActivity(new Intent(this, AiChatActivity.class));
        } else if (id ==R.id.btn_select_date) {
            showDatePickerDialog();
        }
    }

    @Override
    public void onBackPressed() {

        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            // 如果侧边栏打开，关闭侧边栏
            drawerLayout.closeDrawer(GravityCompat.START);
            // 延迟执行返回操作
            new Handler().postDelayed(() -> super.onBackPressed(), 250);
        } else {
            // 强制结束当前活动，避免视图状态卡住
            finish();
        }
    }

    private void flushData(RoundedImageView imageView,TextView name){
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        String savedImageUri = sharedPreferences.getString("user_avatar", null);
        String savedUserName = sharedPreferences.getString("user_name", "");
        if (savedImageUri != null) {
            Glide.with(this).load(Uri.parse(savedImageUri)).into(imageView);
            imageView.setTag(Uri.parse(savedImageUri)); // Set the image URI as a tag
        }
        name.setText(savedUserName);
    }
    @SuppressLint("NonConstantResourceId")
    private void initMenu() {

        navigationView = findViewById(R.id.navigationView);
        //侧边栏全屏显示
        ViewGroup.LayoutParams layoutParams = navigationView.getLayoutParams();
        int width = getResources().getDisplayMetrics().widthPixels;
        layoutParams.width = width;
        navigationView.setLayoutParams(layoutParams);
        //引入header和menu
        navigationView.inflateHeaderView(R.layout.top_main);
        navigationView.inflateMenu(R.menu.drawer);
        //获取头部布局和menu
        View navHeaderView = navigationView.getHeaderView(0);
        LinearLayout header = navHeaderView.findViewById(R.id.img_header_layout);
        imageView = navHeaderView.findViewById(R.id.img_header);
        tv_name = navHeaderView.findViewById(R.id.tv_name);
        flushData(imageView, tv_name);
        header.setOnClickListener(v -> {
            Intent intent = new Intent(this, UserInformationActivity.class);
            startActivity(intent);
        });
        // 设置 item 图标正常显示
        navigationView.setItemIconTintList(null);
        navigationView.setNavigationItemSelectedListener(menuItem -> {
            // 为 item 设置逐个点击事件
            int itemId = menuItem.getItemId();
            if (itemId == R.id.version) {
                Toast.makeText(getBaseContext(), getString(R.string.current_version), Toast.LENGTH_SHORT).show();
            } else if (itemId == R.id.about_us) {
                Intent intent3 = new Intent(this, AboutUsActivity.class);
                startActivity(intent3);
                Toast.makeText(getBaseContext(), "关于我们", Toast.LENGTH_SHORT).show();
            }
            return false;
        });
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
                // 主页内容
                View contentView = drawerLayout.getChildAt(0);
                // 侧边栏
                // slideOffset 值默认是0~1
                contentView.setTranslationX(drawerView.getMeasuredWidth() * slideOffset);
            }

            @Override
            public void onDrawerOpened(@NonNull View drawerView) {
            }

            @Override
            public void onDrawerClosed(@NonNull View drawerView) {
            }

            @Override
            public void onDrawerStateChanged(int newState) {
            }
        });
        // 设置图标动画
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                toolbar,
                R.string.drawer_open,
                R.string.drawer_close
        );
        actionBarDrawerToggle.syncState();
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
    }
    //按日期查询日记时弹出
    private void showDatePickerDialog() {
        LocalDate today = LocalDate.now();
        DatePickerDialog dialog = new DatePickerDialog(this, (view, year, month, day) -> {
            LocalDate selectedDate = LocalDate.of(year, month + 1, day);
            if (selectedDate.isAfter(today)) {
                Toast.makeText(this, "不能选择未来的日期", Toast.LENGTH_SHORT).show();
            } else {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                queryDiariesByDate(LocalDate.parse(selectedDate.format(formatter)));
            }
        }, today.getYear(), today.getMonthValue() - 1, today.getDayOfMonth());

        dialog.getDatePicker().setMaxDate(System.currentTimeMillis());
        dialog.show();
    }

    private void queryDiariesByDate(LocalDate selectedDate) {
        // 查询选中日期的所有日记并跳转
        List<Diary> selectedDiaries = database.getDiariesByDate(selectedDate.toString());
        if (selectedDiaries.isEmpty()) {
            Toast.makeText(MainActivity.this, "没有找到该日期的日记", Toast.LENGTH_SHORT).show();
        } else {
            // 跳转到新的Activity并传递查询到的日记
            Intent intent = new Intent(MainActivity.this, DisplayDiariesActivity.class);
            intent.putParcelableArrayListExtra("selected_diaries", new ArrayList<>(selectedDiaries));  // 将日记列表传递过去
            startActivity(intent);
        }
    }


    public static MainActivity getInstance() {
        return instance;
    }

    public List<DiaryFragment> getDiaryList() {
        return diaryFragments;
    }

    public FragmentAdapter getDiaryPagerAdapter() {
        return diaryPagerAdapter;
    }

    public ViewPager getViewPager() {
        return viewPager;
    }

}